package com.hyk.commonLib.common.utils;

import android.text.TextUtils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;

/**
 * Created by 贺玉琨 on 2019/3/8 0008.
 */
public class UrlUtils {
    /**
     * 获取URL的域名
     */
    public static String getDomain(String url) {
        url = url.replace("http://", "").replace("https://", "");
        if (url.contains("/")) {
            url = url.substring(0, url.indexOf('/'));
        }
        return url;
    }

    /**
     * 获取URL的域名
     */
    public static String getDomainWithProtocol(String url) {
        if (url.contains("/")) {
            int index = url.indexOf('/', url.startsWith("http://") ? 7 : (url.startsWith("https://") ? 8 : 0));
            if (index != -1) {
                url = url.substring(0, index);
            }
        }
        return url;
    }

    /**
     * 基础网址是否相同
     */
    public static boolean equalsIgnoreParams(String urlA, String urlB) {
        if (urlA.contains("?")) {
            urlA = urlA.substring(0, urlA.indexOf('?'));
        }
        if (urlB.contains("?")) {
            urlB = urlB.substring(0, urlB.indexOf('?'));
        }
        return TextUtils.equals(urlA, urlB);
    }

    @SafeVarargs
    public static String appendParams(String url, ImmutablePair<String, String>... pairs) {
        if (ArrayUtils.isEmpty(pairs)) {
            return url;
        }
        StringBuilder builder = new StringBuilder(url);
        if (!url.contains("?")) {
            builder.append("?");
        }
        for (ImmutablePair<String, String> pair : pairs) {
            builder.append(pair.getKey()).append("=").append(pair.getValue()).append("&");
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }
}
